<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>俄罗斯方块 - 用户版</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Arial', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .container {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            max-width: 1200px;
            width: 100%;
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
        }

        .header h1 {
            color: #333;
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .nav-buttons {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin-bottom: 30px;
        }

        .nav-btn {
            padding: 12px 24px;
            border: none;
            border-radius: 25px;
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.3s ease;
        }

        .nav-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }

        .nav-btn.active {
            background: linear-gradient(45deg, #764ba2, #667eea);
        }

        .page {
            display: none;
        }

        .page.active {
            display: block;
        }

        /* 登录注册页面 */
        .auth-container {
            max-width: 400px;
            margin: 0 auto;
            text-align: center;
        }

        .auth-form {
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }

        .form-group {
            margin-bottom: 20px;
            text-align: left;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #333;
            font-weight: bold;
        }

        .form-group input {
            width: 100%;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }

        .form-group input:focus {
            outline: none;
            border-color: #667eea;
        }

        .btn {
            width: 100%;
            padding: 12px;
            border: none;
            border-radius: 8px;
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }

        /* 游戏页面 */
        .game-container {
            display: flex;
            justify-content: center;
            gap: 30px;
            align-items: flex-start;
        }

        .game-board {
            border: 3px solid #333;
            background: #000;
            border-radius: 15px;
        }

        .game-info {
            background: white;
            padding: 20px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            min-width: 200px;
        }

        .game-info h3 {
            color: #333;
            margin-bottom: 15px;
            text-align: center;
        }

        .info-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
            padding: 8px 0;
            border-bottom: 1px solid #eee;
        }

        .game-controls {
            text-align: center;
            margin-top: 20px;
        }

        .control-btn {
            padding: 10px 20px;
            margin: 5px;
            border: none;
            border-radius: 8px;
            background: #667eea;
            color: white;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .control-btn:hover {
            background: #764ba2;
        }

        /* 排行榜页面 */
        .leaderboard {
            max-width: 600px;
            margin: 0 auto;
        }

        .leaderboard table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }

        .leaderboard th,
        .leaderboard td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }

        .leaderboard th {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            font-weight: bold;
        }

        .leaderboard tr:hover {
            background: #f8f9fa;
        }

        .rank-1 { color: #ffd700; font-weight: bold; }
        .rank-2 { color: #c0c0c0; font-weight: bold; }
        .rank-3 { color: #cd7f32; font-weight: bold; }

        /* 管理后台 */
        .admin-container {
            max-width: 800px;
            margin: 0 auto;
        }

        .admin-section {
            background: white;
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }

        .admin-section h3 {
            color: #333;
            margin-bottom: 20px;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
        }

        .user-list {
            max-height: 300px;
            overflow-y: auto;
        }

        .user-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            border-bottom: 1px solid #eee;
        }

        .user-actions button {
            margin-left: 10px;
            padding: 5px 10px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 12px;
        }

        .btn-delete {
            background: #dc3545;
            color: white;
        }

        .btn-promote {
            background: #28a745;
            color: white;
        }

        .message {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            text-align: center;
        }

        .message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .hidden {
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🎮 俄罗斯方块游戏</h1>
            <div class="nav-buttons">
                <button class="nav-btn" onclick="showPage('auth')">登录/注册</button>
                <button class="nav-btn" onclick="showPage('game')">游戏</button>
                <button class="nav-btn" onclick="showPage('leaderboard')">排行榜</button>
                <button class="nav-btn hidden" id="adminBtn" onclick="showPage('admin')">管理后台</button>
                <button class="nav-btn" onclick="logout()">退出</button>
                <button class="nav-btn" onclick="showAdminHelp()" style="background: #28a745;">管理员帮助</button>
            </div>
        </div>

        <!-- 消息提示 -->
        <div id="message" class="message hidden"></div>

        <!-- 登录注册页面 -->
        <div id="authPage" class="page active">
            <div class="auth-container">
                <div class="auth-form">
                    <h2 id="authTitle">用户登录</h2>
                    <form id="authForm">
                        <div class="form-group">
                            <label for="username">用户名:</label>
                            <input type="text" id="username" required>
                        </div>
                        <div class="form-group">
                            <label for="password">密码:</label>
                            <input type="password" id="password" required>
                        </div>
                        <div class="form-group" id="emailGroup" style="display: none;">
                            <label for="email">邮箱:</label>
                            <input type="email" id="email">
                        </div>
                        <button type="submit" class="btn" id="authSubmit">登录</button>
                    </form>
                    <p style="margin-top: 20px;">
                        <span id="authToggle">没有账号？点击注册</span>
                    </p>
                </div>
            </div>
        </div>

        <!-- 游戏页面 -->
        <div id="gamePage" class="page">
            <div class="game-container">
                <canvas id="gameBoard" class="game-board" width="300" height="600" style="background: linear-gradient(135deg, #00204a 0%, #005792 50%, #00bbf0 100%);"></canvas>
                <div class="game-info">
                    <h3>游戏信息</h3>
                    <div class="info-item">
                        <span>玩家:</span>
                        <span id="currentPlayer">-</span>
                    </div>
                    <div class="info-item">
                        <span>分数:</span>
                        <span id="score">0</span>
                    </div>
                    <div class="info-item">
                        <span>等级:</span>
                        <span id="level">1</span>
                    </div>
                    <div class="info-item">
                        <span>消除行数:</span>
                        <span id="lines">0</span>
                    </div>
                    <div class="game-controls">
                        <button class="control-btn" onclick="startGame()">开始游戏</button>
                        <button class="control-btn" onclick="pauseGame()">暂停</button>
                        <button class="control-btn" onclick="resetGame()">重置</button>
                    </div>
                    <div style="margin-top: 20px; font-size: 12px; color: #666;">
                        <p><strong>操作说明:</strong></p>
                        <p>← → 移动</p>
                        <p>↓ 加速下落</p>
                        <p>↑ 旋转</p>
                        <p>空格 直接落下</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 排行榜页面 -->
        <div id="leaderboardPage" class="page">
            <div class="leaderboard">
                <h2 style="text-align: center; margin-bottom: 30px; color: #333;">🏆 积分排行榜</h2>
                <table>
                    <thead>
                        <tr>
                            <th>排名</th>
                            <th>用户名</th>
                            <th>最高分数</th>
                            <th>游戏次数</th>
                            <th>等级</th>
                        </tr>
                    </thead>
                    <tbody id="leaderboardBody">
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 管理后台页面 -->
        <div id="adminPage" class="page">
            <div class="admin-container">
                <h2 style="text-align: center; margin-bottom: 30px; color: #333;">🔧 管理后台</h2>
                
                <div class="admin-section">
                    <h3>用户管理</h3>
                    <div class="user-list" id="userList">
                    </div>
                </div>

                <div class="admin-section">
                    <h3>游戏统计</h3>
                    <div id="gameStats">
                        <p>总用户数: <span id="totalUsers">0</span></p>
                        <p>总游戏次数: <span id="totalGames">0</span></p>
                        <p>平均分数: <span id="avgScore">0</span></p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加管理员帮助模态框 -->
    <div id="adminHelpModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000;">
        <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 30px; border-radius: 15px; max-width: 500px;">
            <h3 style="color: #333; margin-bottom: 20px;">🔐 管理员权限说明</h3>
            <div style="color: #666; line-height: 1.6;">
                <p><strong>如何成为管理员：</strong></p>
                <ol style="margin-left: 20px;">
                    <li>清空浏览器数据（Ctrl+Shift+Del）</li>
                    <li>注册一个新用户账号</li>
                    <li>第一个注册的用户自动成为管理员</li>
                    <li>登录后即可看到"管理后台"按钮</li>
                </ol>
                <p style="margin-top: 15px;"><strong>管理员功能：</strong></p>
                <ul style="margin-left: 20px;">
                    <li>查看和管理所有用户</li>
                    <li>设置/取消管理员权限</li>
                    <li>删除用户账号</li>
                    <li>查看游戏统计数据</li>
                </ul>
            </div>
            <button onclick="closeAdminHelp()" style="margin-top: 20px; padding: 10px 20px; background: #667eea; color: white; border: none; border-radius: 8px; cursor: pointer;">我知道了</button>
        </div>
    </div>

    <script>
        // 游戏状态
        let gameState = {
            board: [],
            currentPiece: null,
            nextPiece: null,
            score: 0,
            level: 1,
            lines: 0,
            isPlaying: false,
            isPaused: false,
            gameLoop: null
        };

        // 用户系统
        let currentUser = null;
        let isLoginMode = true;

        // 俄罗斯方块形状
        const PIECES = [
            [[1,1,1,1]], // I
            [[1,1],[1,1]], // O
            [[0,1,0],[1,1,1]], // T
            [[0,1,1],[1,1,0]], // S
            [[1,1,0],[0,1,1]], // Z
            [[1,0,0],[1,1,1]], // L
            [[0,0,1],[1,1,1]]  // J
        ];

        const COLORS = ['#FF0D72', '#0DC2FF', '#0DFF72', '#F538FF', '#FF8E0D', '#FFE138', '#3877FF'];

        // 初始化
        function init() {
            initBoard();
            loadUserFromStorage();
            updateUI();
            loadLeaderboard();
        }

        // 初始化游戏板
        function initBoard() {
            gameState.board = Array(20).fill().map(() => Array(10).fill(0));
        }

        // 页面切换
        function showPage(pageName) {
            document.querySelectorAll('.page').forEach(page => {
                page.classList.remove('active');
            });
            document.querySelectorAll('.nav-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            
            document.getElementById(pageName + 'Page').classList.add('active');
            event.target.classList.add('active');
        }

        // 显示消息
        function showMessage(text, type = 'success') {
            const messageEl = document.getElementById('message');
            messageEl.textContent = text;
            messageEl.className = `message ${type}`;
            messageEl.classList.remove('hidden');
            
            setTimeout(() => {
                messageEl.classList.add('hidden');
            }, 3000);
        }

        // 用户认证
        document.getElementById('authForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const email = document.getElementById('email').value;
            
            if (isLoginMode) {
                login(username, password);
            } else {
                register(username, password, email);
            }
        });

        // 切换登录/注册模式
        document.getElementById('authToggle').addEventListener('click', function() {
            isLoginMode = !isLoginMode;
            const authTitle = document.getElementById('authTitle');
            const authSubmit = document.getElementById('authSubmit');
            const emailGroup = document.getElementById('emailGroup');
            const authToggle = document.getElementById('authToggle');
            
            if (isLoginMode) {
                authTitle.textContent = '用户登录';
                authSubmit.textContent = '登录';
                emailGroup.style.display = 'none';
                authToggle.textContent = '没有账号？点击注册';
            } else {
                authTitle.textContent = '用户注册';
                authSubmit.textContent = '注册';
                emailGroup.style.display = 'block';
                authToggle.textContent = '已有账号？点击登录';
            }
        });

        // 登录功能
        function login(username, password) {
            const users = JSON.parse(localStorage.getItem('users') || '[]');
            const user = users.find(u => u.username === username && u.password === password);
            
            if (user) {
                currentUser = user;
                localStorage.setItem('currentUser', JSON.stringify(user));
                
                if (user.isAdmin) {
                    showMessage('登录成功！欢迎管理员！');
                } else {
                    showMessage('登录成功！');
                }
                
                updateUI();
                showPage('game');
            } else {
                showMessage('用户名或密码错误！', 'error');
            }
        }

        // 注册功能
        function register(username, password, email) {
            const users = JSON.parse(localStorage.getItem('users') || '[]');
            
            if (users.find(u => u.username === username)) {
                showMessage('用户名已存在！', 'error');
                return;
            }
            
            const newUser = {
                id: Date.now(),
                username: username,
                password: password,
                email: email,
                isAdmin: users.length === 0, // 第一个用户为管理员
                highScore: 0,
                gamesPlayed: 0,
                totalScore: 0,
                level: 1
            };
            
            users.push(newUser);
            localStorage.setItem('users', JSON.stringify(users));
            
            if (newUser.isAdmin) {
                showMessage('注册成功！您是第一个用户，已自动成为管理员！');
            } else {
                showMessage('注册成功！请登录');
            }
            
            isLoginMode = true;
            document.getElementById('authToggle').click();
        }

        // 退出登录
        function logout() {
            currentUser = null;
            localStorage.removeItem('currentUser');
            showMessage('已退出登录');
            updateUI();
            showPage('auth');
        }

        // 从存储加载用户
        function loadUserFromStorage() {
            const userStr = localStorage.getItem('currentUser');
            if (userStr) {
                currentUser = JSON.parse(userStr);
            }
        }

        // 更新UI
        function updateUI() {
            if (currentUser) {
                document.getElementById('currentPlayer').textContent = currentUser.username;
                const adminBtn = document.getElementById('adminBtn');
                adminBtn.classList.toggle('hidden', !currentUser.isAdmin);
                
                // 添加管理员状态提示
                if (currentUser.isAdmin) {
                    document.getElementById('currentPlayer').innerHTML += ' <span style="color: #28a745;">(管理员)</span>';
                }
            } else {
                document.getElementById('currentPlayer').textContent = '-';
                document.getElementById('adminBtn').classList.add('hidden');
            }
        }

        // 游戏功能
        function startGame() {
            if (!currentUser) {
                showMessage('请先登录！', 'error');
                return;
            }
            
            if (gameState.isPlaying) {
                showMessage('游戏正在进行中！', 'error');
                return;
            }
            
            resetGameState();
            gameState.isPlaying = true;
            gameState.currentPiece = createPiece();
            gameState.nextPiece = createPiece();
            
            gameState.gameLoop = setInterval(gameStep, 1000 / gameState.level);
            showMessage('游戏开始！');
        }

        function pauseGame() {
            if (!gameState.isPlaying) {
                showMessage('请先开始游戏！', 'error');
                return;
            }
            
            gameState.isPaused = !gameState.isPaused;
            if (gameState.isPaused) {
                clearInterval(gameState.gameLoop);
                showMessage('游戏暂停');
            } else {
                gameState.gameLoop = setInterval(gameStep, 1000 / gameState.level);
                showMessage('游戏继续');
            }
        }

        function resetGame() {
            clearInterval(gameState.gameLoop);
            resetGameState();
            drawBoard();
            showMessage('游戏重置');
        }

        function resetGameState() {
            gameState.board = Array(20).fill().map(() => Array(10).fill(0));
            gameState.score = 0;
            gameState.level = 1;
            gameState.lines = 0;
            gameState.isPlaying = false;
            gameState.isPaused = false;
            gameState.currentPiece = null;
            gameState.nextPiece = null;
            updateGameInfo();
        }

        function createPiece() {
            const pieceIndex = Math.floor(Math.random() * PIECES.length);
            return {
                shape: PIECES[pieceIndex],
                color: COLORS[pieceIndex],
                x: Math.floor((10 - PIECES[pieceIndex][0].length) / 2),
                y: 0
            };
        }

        function gameStep() {
            if (gameState.isPaused) return;
            
            if (!movePiece(0, 1)) {
                placePiece();
                clearLines();
                gameState.currentPiece = gameState.nextPiece;
                gameState.nextPiece = createPiece();
                
                if (checkCollision()) {
                    endGame();
                }
            }
            
            drawBoard();
        }

        function movePiece(dx, dy) {
            if (!gameState.currentPiece) return false;
            
            const newX = gameState.currentPiece.x + dx;
            const newY = gameState.currentPiece.y + dy;
            
            if (!checkCollision(newX, newY)) {
                gameState.currentPiece.x = newX;
                gameState.currentPiece.y = newY;
                return true;
            }
            
            return false;
        }

        function rotatePiece() {
            if (!gameState.currentPiece) return;
            
            const rotated = gameState.currentPiece.shape[0].map((_, i) =>
                gameState.currentPiece.shape.map(row => row[i]).reverse()
            );
            
            const originalShape = gameState.currentPiece.shape;
            gameState.currentPiece.shape = rotated;
            
            if (checkCollision()) {
                gameState.currentPiece.shape = originalShape;
            }
        }

        function dropPiece() {
            while (movePiece(0, 1)) {
                gameState.score += 2;
            }
        }

        function checkCollision(x = gameState.currentPiece.x, y = gameState.currentPiece.y) {
            if (!gameState.currentPiece) return false;
            
            for (let row = 0; row < gameState.currentPiece.shape.length; row++) {
                for (let col = 0; col < gameState.currentPiece.shape[row].length; col++) {
                    if (gameState.currentPiece.shape[row][col]) {
                        const newX = x + col;
                        const newY = y + row;
                        
                        if (newX < 0 || newX >= 10 || newY >= 20) {
                            return true;
                        }
                        
                        if (newY >= 0 && gameState.board[newY][newX]) {
                            return true;
                        }
                    }
                }
            }
            
            return false;
        }

        function placePiece() {
            if (!gameState.currentPiece) return;
            
            for (let row = 0; row < gameState.currentPiece.shape.length; row++) {
                for (let col = 0; col < gameState.currentPiece.shape[row].length; col++) {
                    if (gameState.currentPiece.shape[row][col]) {
                        const x = gameState.currentPiece.x + col;
                        const y = gameState.currentPiece.y + row;
                        
                        if (y >= 0) {
                            gameState.board[y][x] = gameState.currentPiece.color;
                        }
                    }
                }
            }
        }

        function clearLines() {
            let linesCleared = 0;
            
            for (let row = gameState.board.length - 1; row >= 0; row--) {
                if (gameState.board[row].every(cell => cell !== 0)) {
                    gameState.board.splice(row, 1);
                    gameState.board.unshift(Array(10).fill(0));
                    linesCleared++;
                    row++; // 重新检查当前行
                }
            }
            
            if (linesCleared > 0) {
                gameState.lines += linesCleared;
                gameState.score += linesCleared * 100 * gameState.level;
                gameState.level = Math.floor(gameState.lines / 10) + 1;
                
                // 调整游戏速度
                clearInterval(gameState.gameLoop);
                gameState.gameLoop = setInterval(gameStep, 1000 / gameState.level);
                
                updateGameInfo();
            }
        }

        function endGame() {
            clearInterval(gameState.gameLoop);
            gameState.isPlaying = false;
            
            // 更新用户统计
            updateUserStats();
            
            showMessage(`游戏结束！最终分数: ${gameState.score}`);
        }

        function updateUserStats() {
            if (!currentUser) return;
            
            const users = JSON.parse(localStorage.getItem('users') || '[]');
            const userIndex = users.findIndex(u => u.id === currentUser.id);
            
            if (userIndex !== -1) {
                const user = users[userIndex];
                user.gamesPlayed++;
                user.totalScore += gameState.score;
                user.highScore = Math.max(user.highScore, gameState.score);
                user.level = Math.max(user.level, gameState.level);
                
                currentUser = user;
                localStorage.setItem('currentUser', JSON.stringify(user));
                localStorage.setItem('users', JSON.stringify(users));
                
                updateGameInfo();
                loadLeaderboard();
            }
        }

        function updateGameInfo() {
            document.getElementById('score').textContent = gameState.score;
            document.getElementById('level').textContent = gameState.level;
            document.getElementById('lines').textContent = gameState.lines;
        }

        function drawBoard() {
            const canvas = document.getElementById('gameBoard');
            const ctx = canvas.getContext('2d');
            
            // 清空画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 绘制游戏板
            for (let row = 0; row < gameState.board.length; row++) {
                for (let col = 0; col < gameState.board[row].length; col++) {
                    if (gameState.board[row][col]) {
                        ctx.fillStyle = gameState.board[row][col];
                        ctx.fillRect(col * 30, row * 30, 30, 30);
                        ctx.strokeStyle = '#333';
                        ctx.strokeRect(col * 30, row * 30, 30, 30);
                    }
                }
            }
            
            // 绘制当前方块
            if (gameState.currentPiece) {
                ctx.fillStyle = gameState.currentPiece.color;
                for (let row = 0; row < gameState.currentPiece.shape.length; row++) {
                    for (let col = 0; col < gameState.currentPiece.shape[row].length; col++) {
                        if (gameState.currentPiece.shape[row][col]) {
                            const x = (gameState.currentPiece.x + col) * 30;
                            const y = (gameState.currentPiece.y + row) * 30;
                            ctx.fillRect(x, y, 30, 30);
                            ctx.strokeStyle = '#333';
                            ctx.strokeRect(x, y, 30, 30);
                        }
                    }
                }
            }
        }

        // 键盘控制
        document.addEventListener('keydown', function(e) {
            if (!gameState.isPlaying || gameState.isPaused) return;
            
            switch(e.key) {
                case 'ArrowLeft':
                    movePiece(-1, 0);
                    break;
                case 'ArrowRight':
                    movePiece(1, 0);
                    break;
                case 'ArrowDown':
                    movePiece(0, 1);
                    break;
                case 'ArrowUp':
                    rotatePiece();
                    break;
                case ' ':
                    e.preventDefault();
                    dropPiece();
                    break;
            }
            
            drawBoard();
        });

        // 排行榜
        function loadLeaderboard() {
            const users = JSON.parse(localStorage.getItem('users') || '[]');
            const sortedUsers = users.sort((a, b) => b.highScore - a.highScore).slice(0, 10);
            
            const tbody = document.getElementById('leaderboardBody');
            tbody.innerHTML = '';
            
            sortedUsers.forEach((user, index) => {
                const row = document.createElement('tr');
                const rankClass = index < 3 ? `rank-${index + 1}` : '';
                
                row.innerHTML = `
                    <td class="${rankClass}">${index + 1}</td>
                    <td>${user.username}</td>
                    <td>${user.highScore}</td>
                    <td>${user.gamesPlayed}</td>
                    <td>${user.level}</td>
                `;
                
                tbody.appendChild(row);
            });
        }

        // 管理后台
        function loadAdminData() {
            if (!currentUser || !currentUser.isAdmin) return;
            
            loadUserList();
            loadGameStats();
        }

        function loadUserList() {
            const users = JSON.parse(localStorage.getItem('users') || '[]');
            const userList = document.getElementById('userList');
            
            userList.innerHTML = '';
            
            users.forEach(user => {
                const userItem = document.createElement('div');
                userItem.className = 'user-item';
                userItem.innerHTML = `
                    <span>${user.username} ${user.isAdmin ? '(管理员)' : ''}</span>
                    <div class="user-actions">
                        <button class="btn-promote" onclick="toggleAdmin(${user.id})">
                            ${user.isAdmin ? '取消管理员' : '设为管理员'}
                        </button>
                        <button class="btn-delete" onclick="deleteUser(${user.id})">删除</button>
                    </div>
                `;
                userList.appendChild(userItem);
            });
        }

        function loadGameStats() {
            const users = JSON.parse(localStorage.getItem('users') || '[]');
            const totalUsers = users.length;
            const totalGames = users.reduce((sum, user) => sum + user.gamesPlayed, 0);
            const totalScore = users.reduce((sum, user) => sum + user.totalScore, 0);
            const avgScore = totalGames > 0 ? Math.round(totalScore / totalGames) : 0;
            
            document.getElementById('totalUsers').textContent = totalUsers;
            document.getElementById('totalGames').textContent = totalGames;
            document.getElementById('avgScore').textContent = avgScore;
        }

        function toggleAdmin(userId) {
            const users = JSON.parse(localStorage.getItem('users') || '[]');
            const userIndex = users.findIndex(u => u.id === userId);
            
            if (userIndex !== -1) {
                users[userIndex].isAdmin = !users[userIndex].isAdmin;
                localStorage.setItem('users', JSON.stringify(users));
                
                if (currentUser.id === userId) {
                    currentUser.isAdmin = users[userIndex].isAdmin;
                    localStorage.setItem('currentUser', JSON.stringify(currentUser));
                    updateUI();
                }
                
                loadAdminData();
                showMessage('用户权限已更新');
            }
        }

        function deleteUser(userId) {
            if (confirm('确定要删除这个用户吗？')) {
                const users = JSON.parse(localStorage.getItem('users') || '[]');
                const filteredUsers = users.filter(u => u.id !== userId);
                localStorage.setItem('users', JSON.stringify(filteredUsers));
                
                if (currentUser.id === userId) {
                    logout();
                }
                
                loadAdminData();
                loadLeaderboard();
                showMessage('用户已删除');
            }
        }

        // 管理员帮助功能
        function showAdminHelp() {
            document.getElementById('adminHelpModal').style.display = 'block';
        }

        function closeAdminHelp() {
            document.getElementById('adminHelpModal').style.display = 'none';
        }

        // 页面加载时初始化
        window.addEventListener('load', function() {
            init();
            
            // 如果已登录，显示游戏页面
            if (currentUser) {
                showPage('game');
            }
            
            // 管理后台数据加载
            if (currentUser && currentUser.isAdmin) {
                loadAdminData();
            }
        });

        // 页面切换时加载数据
        document.addEventListener('click', function(e) {
            if (e.target.classList.contains('nav-btn')) {
                setTimeout(() => {
                    if (e.target.textContent === '排行榜') {
                        loadLeaderboard();
                    } else if (e.target.textContent === '管理后台') {
                        loadAdminData();
                    }
                }, 100);
            }
        });
    </script>
</body>
</html>